<?php
/**
 * custom post for Event
 */
register_post_type('vs_event', array(	'label' => 'Events','description' => '','public' => true,'show_ui' => true,'show_in_menu' => true,'capability_type' => 'post','hierarchical' => false,'rewrite' => array('slug' => 'eventscalendar'),'query_var' => true,'exclude_from_search' => true,'supports' => array('title', 'editor'),'labels' => array (
  'name' => 'Events',
  'singular_name' => 'Event',
  'menu_name' => 'Events',
  'add_new' => 'Add Event',
  'add_new_item' => 'Add New Event',
  'edit' => 'Edit',
  'edit_item' => 'Edit Event',
  'new_item' => 'New Event',
  'view' => 'View Event',
  'view_item' => 'View Event',
  'search_items' => 'Search Events',
  'not_found' => 'No Events Found',
  'not_found_in_trash' => 'No Events Found in Trash',
  'parent' => 'Parent Event',
),) );

add_action("admin_init", "admin_init");
 
function admin_init(){
  add_meta_box("events_meta", "Event Details", "events_meta", "vs_event", "normal", "low");
  wp_enqueue_script('datepickerScript', get_bloginfo('template_url') . '/jqueryui/js/jquery-ui-1.8.23.custom.min.js', array('jquery','jquery-ui-core'));
	wp_enqueue_style('datepickerStyle', get_bloginfo('template_url') . '/jqueryui/css/ui-lightness/jquery-ui-1.8.23.custom.css');
}

//ADD MENU FOR IMPORT FROM EXCEL
add_action('admin_menu', 'register_vs_event_menu');
function register_vs_event_menu()
{
	add_submenu_page( 'edit.php?post_type=vs_event', 'Import events from excel file', 'Import from Excel', 'manage_options', 'vs_event_excel', 'vs_event_excel');
}

function vs_event_excel(){
	echo '<h2>Import event from excel file(*.xls)</h2>';
	if($_POST['upload'])
	{	do_upload();
		show_events_from_excel();
	}
	else if($_POST['add'])
	{
		do_add_event();
	}
	//show_events_from_excel();
	else show_upload_form();
}
function do_add_event()
{
	require_once 'excel/reader.php';
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('UTF-8');
	$data->read('../wp-content/themes/visitsandiego/eventexcelfiles/data.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$count = 0;
	foreach($_POST['event'] as $ev)
	{
		$title = $data->sheets[0]['cells'][$ev][3];
		$type = $data->sheets[0]['cells'][$ev][4];
		$time = xl2timestamp($data->sheets[0]['cells'][$ev][5]);
		$duration = $data->sheets[0]['cells'][$ev][6];
		$duration = $duration - 1;
		$end = strtotime("+$duration day", $time);
		$attendance = $data->sheets[0]['cells'][$ev][7];
		$isprivate = ($data->sheets[0]['cells'][$ev][8] == "No")?1:0;
		$link = $data->sheets[0]['cells'][$ev][9];
		$my_post = array(
			'post_title'    => $title,
			'post_status'   => 'publish',
			'post_author'   => 1,
			'post_type' => 'vs_event'
		);
		$postID = wp_insert_post( $my_post );
		update_post_meta($postID , "type", $type);
		update_post_meta($postID , "attendance", $attendance);
		update_post_meta($postID , "begindate", $time);
		update_post_meta($postID , "enddate", $end);
		update_post_meta($postID , "website", $link);
		update_post_meta($postID , "isprivate", $isprivate);
		$count++;
	}
	echo "<b>Inserted $count events successful</b>";
}
function show_upload_form()
{
	?>
	<form action="" enctype="multipart/form-data" method="POST">
		<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
		Choose a file to upload: <input name="uploadedfile" type="file" /><br />
		<input type="submit" value="Upload File" name="upload"/>
	</form>
	<?php
}

function xl2timestamp($xl_date)
{
$timestamp = ($xl_date - 25569) * 86400;
return $timestamp;
}

function do_upload()
{
	$target = "../wp-content/themes/visitsandiego/eventexcelfiles/";
	$targetx = $target . 'data.xls';
	if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $targetx))
	{
		echo "Failed to upload file";
	}
}

function show_events_from_excel()
{
	require_once 'excel/reader.php';
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('UTF-8');
	$data->read('../wp-content/themes/visitsandiego/eventexcelfiles/data.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	//First row is header
	?>
	<form action="" method="POST" name="selectevent">
	<table class="widefat" cellspacing="0">
		<thead>
			<tr>
				<th id="cb" class="manage-column column-cb check-column" scope="col"><input type="checkbox"></th>
				<th><span>Event</span></th>
				<th><span>Type</span></th>
				<th><span>Day</span></th>
			</tr>
		</thead>
		<tbody>
	<?php
		for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
			echo '<tr>
					<th class="check-column" scope="row" style="padding: 5px 0 0;">
						<input type="checkbox" value="'.$i.'" name="event[]" checked>
					</th>';
			echo '<td><b>'.$data->sheets[0]['cells'][$i][3].'</b></td>';
			echo '<td><b>'.$data->sheets[0]['cells'][$i][4].'</b></td>';
			$time = xl2timestamp($data->sheets[0]['cells'][$i][5]);
			echo '<td><b>'.date('m/d/Y', $time).'</b></td>';
			echo '</tr>';
		}
	?>
		</tbody>
	</table>
	<br/>
	<input type="submit" value="Add selected"  class="button-secondary" name="add"/>
	</form>
	<?
}

function events_meta() {
  global $post;
  $custom = get_post_custom($post->ID);
  $begindate = $custom["begindate"][0];
  $enddate = $custom["enddate"][0];
  $attendance = $custom["attendance"][0];
  $website = $custom["website"][0];
  $isprivate = $custom["isprivate"][0];
  $type = $custom["type"][0];
  ?>
  <script type="text/javascript">
	var $j = jQuery.noConflict();
	$j(function() {
		$j("#begindate").datepicker();
		$j("#enddate").datepicker();

	});
  </script>
  <style>
	#event_meta tr th {text-align: right;}
  </style>
  <table id="event_meta">
	<tr><th><label for="type">Type:</label></th><td><input style="width: 360px" type="text" name="type" id="type" value="<?php echo $type; ?>"></input></td></tr>
	<tr><th><label for="attendance">Attendance:</label></th><td><input type="text" name="attendance" id="attendance" value="<?php echo $attendance; ?>"></input></td></tr>
	<tr><th><label for="begindate">Begin date:</label></th><td><input type="text" name="begindate" id="begindate" value="<?php echo $begindate?date('m/d/Y',$begindate):date('m/d/Y'); ?>"></input></td></tr>
	<tr><th><label for="enddate">End date:</label></th><td><input type="text" name="enddate" id="enddate" value="<?php echo $enddate?date('m/d/Y',$enddate):date('m/d/Y'); ?>"></input></td></tr>
	<tr><th><label for="website">Website:</label></th><td><input style="width: 300px" type="text" name="website" id="website" value="<?php echo $website; ?>"></input></td></tr>
	<tr><th><label for="isprivate">Is private:</label></th><td><input type="checkbox" name="isprivate" id="isprivate" <?php if($isprivate) echo "checked" ?> value="1"> Private</input></td></tr>
  </table>
  <?php
}
add_action('save_post', 'save_details');
function save_details(){
	global $post;
	if($_POST['post_type'] != "vs_event") return;
	update_post_meta($post->ID, "type", $_POST["type"]);
	update_post_meta($post->ID, "attendance", $_POST["attendance"]);
	update_post_meta($post->ID, "begindate", strtotime($_POST["begindate"]."0:0:0"));
	update_post_meta($post->ID, "enddate", strtotime($_POST["enddate"]."0:0:0"));
	update_post_meta($post->ID, "website", $_POST["website"]);
	update_post_meta($post->ID, "isprivate", $_POST["isprivate"]);
}

add_action("manage_vs_event_posts_custom_column",  "event_custom_columns");
add_filter("manage_edit-vs_event_columns", "event_edit_columns");
 
function event_edit_columns($columns){
  $columns = array(
    "cb" => '<input type="checkbox" />',
    "title" => "Title",
    "type" => "Type",
    "attendance" => "Attendance",
    "begindate" => "Begin date",
    "enddate" => "End date",
    "isprivate" => "Private",
  );
 
  return $columns;
}
function event_custom_columns($column){
	global $post;
	$custom = get_post_custom();
	
	switch ($column) {
	case "type":
		echo $custom["type"][0];
		break;
	case "attendance":
		echo $custom["attendance"][0];
		break;
	case "begindate":
		echo date('m/d/Y', $custom["begindate"][0]);
		break;
	case "enddate":
		echo date('m/d/Y', $custom["enddate"][0]);
		break;
	case "isprivate":
		echo $custom["isprivate"][0]?"True":"False";
		break;
	}
}


add_filter('manage_edit-vs_event_sortable_columns', 'vs_event_sortable_columns');
function vs_event_sortable_columns( $columns ){
  $columns['type'] = 'type';
  $columns['attendance'] = 'attendance';
  $columns['begindate'] = 'begindate';
  $columns['enddate'] = 'enddate';
  return $columns;
}

function vs_event_get_scopes(){
	$scopes = array(
		'all' => 'All events',
		'future' => 'Future events',
		'past' => 'Past events',
		'next' => 'Next events',
		'week' => 'Events this week',
		'next-week' => 'Events next week',
		'previous-week' => 'Events previous week',
		'month'  => 'Events within this month',
		'2-months' => 'Events within 2 months',
		'6-months' => 'Events within 6 months',
		'18-months' => 'Events within 18 months'
	);
	return apply_filters('em_get_scopes',$scopes);
}

add_action('restrict_manage_posts', 'restrict_manage_posts');
function restrict_manage_posts(){
	global $wp_query;
	if( $wp_query->query_vars['post_type'] == 'vs_event'){
		?>
		<style>
			.tablenav select[name="m"] { display:none; }
		</style>
		<select name="scope">
			<?php
			$scope = (!empty($wp_query->query_vars['scope'])) ? $wp_query->query_vars['scope']:'all';
			foreach ( vs_event_get_scopes() as $key => $value ) {
				$selected = "";
				if ($key == $scope)
					$selected = "selected='selected'";
				echo "<option value='$key' $selected>$value</option>  ";
			}
			?>
		</select>
		<?php
	}
}
add_filter('parse_query', 'parse_query');
function parse_query( ){
	global $wp_query;
	//Scoping
	if( !empty($wp_query->query_vars['post_type']) && ($wp_query->query_vars['post_type'] == "vs_event") && (empty($wp_query->query_vars['post_status']) || !in_array($wp_query->query_vars['post_status'],array('trash','pending','draft'))) ) {
		//Let's deal with the scope - default is future
		$scope = $wp_query->query_vars['scope'] = (!empty($_REQUEST['scope'])) ? $_REQUEST['scope']:'all';
		//echo $scope;
		$query = array();
		$time = current_time('timestamp');
		if ($scope == "future"){
			$today = strtotime(date('Y-m-d', $time));
			$query[] = array( 'key' => 'begindate', 'value' => $today, 'compare' => '>=' );
		}elseif ($scope == "past"){
			$today = strtotime(date('Y-m-d', $time));
			$query[] = array( 'key' => 'enddate', 'value' => $today, 'compare' => '<');
		}elseif ($scope == "next"){
			$today = strtotime(date('Y-m-d', $time));
			$query[] = array( 'key' => 'enddate', 'value' => $today, 'compare' => '>=');
		}elseif ($scope == "week"){
			$beginweek = strtotime("0:0:0",time()-date('w')*24*3600);
			$endweek = strtotime("+1 week", $beginweek);
			$query[] = array( 'key' => 'begindate', 'value' => array($beginweek,$endweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
			$query[] = array( 'key' => 'enddate', 'value' => array($beginweek,$endweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
		}elseif ($scope == "next-week"){
			$thisweek = strtotime("0:0:0",time()-date('w')*24*3600);
			$beginweek = strtotime("+1 week", $thisweek);
			$endweek = strtotime("+1 week", $beginweek);
			$query[] = array( 'key' => 'begindate', 'value' => array($beginweek,$endweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
			$query[] = array( 'key' => 'enddate', 'value' => array($beginweek,$endweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
		}elseif ($scope == "previous-week"){
			$thisweek = strtotime("0:0:0",time()-date('w')*24*3600);
			$beginweek = strtotime("-1 week", $thisweek);
			$query[] = array( 'key' => 'begindate', 'value' => array($beginweek,$thisweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
			$query[] = array( 'key' => 'enddate', 'value' => array($beginweek,$thisweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
		}elseif ($scope == "month"){
			$begintime = strtotime(date("n").'/1/'.date("Y")." 0:0:0");
			$endtime = strtotime("+1 month", $begintime);
			$query[] = array( 'key' => 'begindate', 'value' => array($begintime,$endtime), 'type' => 'numeric', 'compare' => 'BETWEEN' );
			$query[] = array( 'key' => 'enddate', 'value' => array($begintime,$endtime), 'type' => 'numeric', 'compare' => 'BETWEEN' );
		}elseif ($scope == "2-months"){
			$begintime = strtotime(date("n").'/1/'.date("Y")." 0:0:0");
			$endtime = strtotime("+2 month", $begintime);
			$query[] = array( 'key' => 'begindate', 'value' => array($begintime,$endtime), 'type' => 'numeric', 'compare' => 'BETWEEN' );
			$query[] = array( 'key' => 'enddate', 'value' => array($begintime,$endtime), 'type' => 'numeric', 'compare' => 'BETWEEN' );
		}elseif ($scope == "6-months"){
			$begintime = strtotime(date("n").'/1/'.date("Y")." 0:0:0");
			$endtime = strtotime("+6 month", $begintime);
			$query[] = array( 'key' => 'begindate', 'value' => array($begintime,$endtime), 'type' => 'numeric', 'compare' => 'BETWEEN' );
			$query[] = array( 'key' => 'enddate', 'value' => array($begintime,$endtime), 'type' => 'numeric', 'compare' => 'BETWEEN' );
		}elseif ($scope == "18-months"){
			$begintime = strtotime(date("n").'/1/'.date("Y")." 0:0:0");
			$endtime = strtotime("+18 month", $begintime);
			$query[] = array( 'key' => 'begindate', 'value' => array($begintime,$endtime), 'type' => 'numeric', 'compare' => 'BETWEEN' );
			$query[] = array( 'key' => 'enddate', 'value' => array($begintime,$endtime), 'type' => 'numeric', 'compare' => 'BETWEEN' );
		}elseif( preg_match('/(\d\d?)\-weeks/',$scope,$matches) ){
			$weeks_to_add = $matches[1];
			//$weeks_to_add++;
			$currentweek = strtotime("0:0:0",time()-date('w')*24*3600);
			$beginweek = strtotime("+$weeks_to_add week", $currentweek);
			$endweek = strtotime("+7 day", $beginweek);
			$query[] = array( 'key' => 'begindate', 'value' => array($beginweek,$endweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
			$query[] = array( 'key' => 'enddate', 'value' => array($beginweek,$endweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
		}
		if($_REQUEST['enddate'] && $_REQUEST['startdate'])
		{
			$beginweek = strtotime($_REQUEST['startdate']);
			$endweek = strtotime($_REQUEST['enddate']);
			$query[] = array( 'key' => 'begindate', 'value' => array($beginweek,$endweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
			$query[] = array( 'key' => 'enddate', 'value' => array($beginweek,$endweek), 'type' => 'numeric', 'compare' => 'BETWEEN' );
		}
		if( !empty($query) && is_array($query) ){
			$query['relation'] = 'OR';
			print_r($query);
			$wp_query->query_vars['meta_query'] = $query;
		}
		if( is_admin() ){
			//admin areas don't need special ordering, so make it simple
			$wp_query->query_vars['orderby'] = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby']:'ID';
			$wp_query->query_vars['order'] = (!empty($_REQUEST['order'])) ? $_REQUEST['order']:'DEC';
		}else{
			$wp_query->query_vars['orderby'] = 'meta_value_num';
			$wp_query->query_vars['meta_key'] = 'begindate';  		
			$wp_query->query_vars['order'] = 'ASC';
		}
	}elseif( !empty($wp_query->query_vars['post_type']) && $wp_query->query_vars['post_type'] == "vs_event" ){
		$wp_query->query_vars['scope'] = 'all';
	}

}
function add_my_var($public_query_vars) {
    $public_query_vars[] = 'week';
    return $public_query_vars;
}

add_filter('query_vars', 'add_my_var');
add_rewrite_rule('eventscalendar/week/([^/]+)/?$', 'index.php?pagename=eventscalendar&week=$matches[1]','top');


add_filter( 'posts_where', 'title_vs_event_like_posts_where', 10, 2 );
function title_vs_event_like_posts_where( $where, &$wp_query ) {
    global $wpdb;
    if ( $post_vs_event_title_like = $wp_query->get( 'post_vs_event_title_like' ) ) {
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $post_vs_event_title_like ) ) . '%\'';
    }
    return $where;
}


?>